package com.toman.ui.work.workplan;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseMonthDayPlanEntity;
import com.toman.JavaBean.DeviceHouseMonthPlanEntity;
import com.toman.R;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.toolbar.ToolBarActivity;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class WorkshopMonthPlanEditActivity extends ToolBarActivity {
    CommonAdapter<DeviceHouseMonthDayPlanEntity> adapter;
    List<DeviceHouseMonthDayPlanEntity> list = new ArrayList<>();
    DeviceHouseMonthPlanEntity bean = new DeviceHouseMonthPlanEntity();
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.rl_product_dep)
    RelativeLayout rlProductDep;
    @BindView(R.id.tv_workday)
    TextView tvWorkday;
    @BindView(R.id.rl_product_workday)
    RelativeLayout rlProductWorkday;
    @BindView(R.id.et_month_plan)
    EditText etMonthPlan;
    @BindView(R.id.et_day_plan)
    EditText etDayPlan;
    @BindView(R.id.tv_title)
    LinearLayout tvTitle;
    @BindView(R.id.lv)
    RecyclerView lv;
    String monthPlanId = "";
    AlertDialog.Builder builder = null;
    @BindView(R.id.tv_ok)
    TextView tvOk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workshop_month_plan_add);
        ButterKnife.bind(this);
        initIntent();
        initView();

    }

    private void initIntent() {
        list = (List<DeviceHouseMonthDayPlanEntity>) getIntent().getSerializableExtra("list");
        bean = (DeviceHouseMonthPlanEntity) getIntent().getSerializableExtra("bean");
        monthPlanId = bean.getId() + "";
        tvWorkday.setText(bean.getMonth());
        etMonthPlan.setText(bean.getPlanOutput() + "");
        tvDep.setText(bean.getDepartmentName());
        tvOk.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
        tvOk.getPaint().setAntiAlias(true);//抗锯齿

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
        baseEnum = BaseEnum.WORKSHOPMONTHPLAN;
        initToolBar(baseEnum.edit());
        initAdapter();
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
        etDayPlan.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<DeviceHouseMonthDayPlanEntity>(this, R.layout.item_workshop_month_plan_add, list) {
            @Override
            protected void convert(ViewHolder holder, DeviceHouseMonthDayPlanEntity item, final int position) {
                try {
                    holder.setText(R.id.tv_date, item.getDay().substring(5));
                    String strDate = item.getDay();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");// 日期格式
                    Date date = format.parse(strDate);
                    holder.setText(R.id.tv_week, TimeUtil.getWeek(date));

                } catch (Exception e) {
                    e.printStackTrace();
                }

                EditText et_plan = holder.getView(R.id.et_plan);
                if (et_plan.getTag() instanceof TextWatcher) {
                    et_plan.removeTextChangedListener(((TextWatcher) et_plan.getTag()));
                }
                et_plan.setText(item.getPlanOutput() + "");

                TextWatcher textWatcher = new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                        try {
                            item.setPlanOutput(Integer.valueOf(s.toString()));
//                            list.get(position).setPlanOutput(Integer.parseInt(s.toString()));
                        } catch (Exception e) {
                            item.setPlanOutput(0);
//                            list.get(position).setPlanOutput(0);
                        }

                    }
                };

                et_plan.addTextChangedListener(textWatcher);
                et_plan.setTag(textWatcher);


            }
        };
    }


    @OnClick({R.id.rl_product_dep, R.id.rl_product_workday})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_product_dep:
                DialogUtils.showDialog(this, NetworkEnum.DEP, mCompanyId, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        bean.setDepartmentId(Long.valueOf(bean1.getID()));
                        tvDep.setText(bean1.getName());
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.rl_product_workday:

//             if (null==builder){

                ViewUtil.getdays(this, token, list, tvWorkday, false, new DefaultAcitonCallback() {
                    @Override
                    public void run() {
                        super.run();
                        adapter.notifyDataSetChanged();
                    }
                });
//             }
//                else {
//                 builder.show();
//             }
                break;
        }
    }

    public void add() {
        String[] item = new String[]{"部门", "工作日", "月计划数"};//直接初始化
        if (ViewUtil.isNull(getApplicationContext(), item, tvDep, tvWorkday, etMonthPlan)) {
            return;
        }
        if (list.isEmpty()) {
            ToastUtil.makeText(getApplicationContext(), "工作日不得为空");
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", list.get(0).getMonthPlanId());

        map.put("departmentId", bean.getDepartmentId() + "");
        map.put("month", list.get(0).getDay().substring(0, 7));
        map.put("workDayPlanList", list);
        map.put("planOutput", etMonthPlan.getText().toString());

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.devicehousemonthplan_update)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            SPUtils.put(getApplicationContext(), baseEnum.update(), true);

                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }

    @OnClick(R.id.tv_ok)
    public void onViewClicked() {
        DialogUtils.showDialog(this, "确认要将所有数据设置为默认值吗", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for (DeviceHouseMonthDayPlanEntity entity : list) {
                    try {
                        entity.setPlanOutput(Integer.valueOf(etDayPlan.getText().toString()));
                    } catch (Exception e) {
                        entity.setPlanOutput(0);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });

    }
}
